package com.hframe.http.client;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.hframe.Json.DataToJson;
import com.hframe.data.DRef;
import com.hframe.other.MsgException;
import com.hframe.type.T;
import com.hframe.type.TData;
import com.hframe.type.TInt;
import com.hframe.type.TString;

import java.util.ArrayList;

/**
 * Created by heqian on 17-3-8.
 */
public class ResponseData extends DRef<ResponseData> {
    public TInt code = new TInt(0);
    public TString msg = new TString();
    public T<?> data = new T<>();
    private JsonElement json = null;

    public ResponseData(Integer code, String msg) {
        this.code.set(code);
        this.msg.set(msg);
    }

    public ResponseData(T<?> data, String msg) {
        this.msg.set(msg);
        this.data = data;
    }

    public ResponseData(String msg) {
        this.msg.set(msg);
    }

    public ResponseData(MsgException e) {
        code.set(e.getError());
        msg.set(e.getMessage());
    }

    public void setCode(TInt code) {
        this.code = code;
    }

    public void setMsg(TString msg) {
        this.msg = msg;
    }

    public void setData(T<?> data) {
        if (null == data)
            this.data.set(null);
        else
            this.data = data;
        this.json = null;
    }

    public void setData(DRef<?> data) {
        if (null == data)
            this.data.set(null);
        else {
            TData typaData = new TData<>(DRef.class);
            typaData.set(data);
            this.data = typaData;
        }
        this.json = null;
    }

    public void setData(JsonElement json) {
        this.json = json;
        this.data.set(null);
    }

    public JsonElement getJson() {
        ArrayList<String> array = new ArrayList<>();
        array.add("code");
        array.add("msg");
        if (null != data && !data.isEmpty())
            array.add("data");

        String keys[] = new String[array.size()];
        array.toArray(keys);
        JsonObject outJosn = (JsonObject) DataToJson.convert(this, keys);

        if (null != this.json) {
            outJosn.add("data", this.json);
        }
        return outJosn;
    }
}
